using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using System.Web;
using System.Threading;
using System.Diagnostics;
using System.Web.UI.WebControls;

namespace CKS.EBE.Search
{
    public class SearchBox : CKS.EBE.WebControls.BaseForm
    {
        protected string _resultsUrl = "~site/search.aspx";
        private string _queryParameter = "k";
        private string _displayQueryParameter;

        public string DisplayQueryParameter
        {
            get { return ((string.IsNullOrEmpty(_displayQueryParameter)) ? QueryParameter : _displayQueryParameter); }
            set { _displayQueryParameter = value; }
        }

        public string QueryParameter
        {
            get { return _queryParameter; }
            set { _queryParameter = value; }
        }

        public string ResultsUrl
        {
            get { return _resultsUrl; }
            set { _resultsUrl = value; }
        }

        protected override void OnLoad(EventArgs e)
        {
            EnsureChildControls();
            if (!Page.IsPostBack)
            {
                try
                {
                    ((TextBox)FindFormControl("idSearchText")).Text = Page.Request[QueryParameter];
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex);
                }
            }
        }

        protected override void OnSubmit(object sender, EventArgs e)
        {
            try
            {
                string sURL = ResultsUrl;

                if (sURL.StartsWith("~site")) sURL = sURL.Replace("~site", SPContext.Current.Web.ServerRelativeUrl);

                sURL += "?" + QueryParameter + "=" + TextBoxValue("idSearchText");
                HttpContext.Current.Response.Redirect(sURL);
            }
            catch (Exception ex)
            {
                if (ex is ThreadAbortException) return;

                Trace.WriteLine(ex);
            }
            

        }

    }
}
